﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Lion.WeiXin.Core.Models;
using Lion.WeiXin.Core.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Lion.WeiXin.Tools.Log;
using System.Collections;
using System.IO;
namespace Lion.WeiXin.Controllers
{
    [PermissionFilter]
    public class TemplateController : Controller
    {
        //数据访问上线文对象
        DBContext db;
        public TemplateController() : this(null) { }

        /// <summary>
        /// 模拟测试使用
        /// </summary>
        /// <param name="mockDB"></param>
        public TemplateController(DBContext mockDB)
        {
            if (mockDB == null)
            { db = new DBContext(); }
            else
            {
                db = mockDB;
            }
        }

        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        ///  获取分页列表数据
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="msgType"></param>
        /// <param name="currentPage"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public string GetPageList(string name, int currentPage, int pageSize)
        {
            //数据量少的，直接查全部数据分页展示           
            List<TemplateModel> list = db.Templates.GetList(string.Empty);
            int totalCount = list.Count;
            //如果传入条件参数
            name = HttpUtility.UrlDecode(name);
            if (!string.IsNullOrEmpty(name))
            {
                list = list.Where(n => n.Name.Contains(name)).Skip((currentPage - 1) * pageSize).Take(pageSize).ToList();
            }
            else
            {
                list = list.Skip((currentPage - 1) * pageSize).Take(pageSize).ToList();
            }

            string jsonResult = JsonConvert.SerializeObject(list, new IsoDateTimeConverter());
            jsonResult = "{\"total\":" + totalCount + "," + "\"data\":" + jsonResult + "}";
            return jsonResult;
        }

        public ActionResult Show(int ID)
        {
            TemplateModel model = db.Templates.GetModel(ID);
            InitType(model.TypeCode);
            return View(model);
        }

        public ActionResult Create()
        {
            //获取网站模板类型
            InitType("000");
            return View();
        }

        private void InitType(string selectID)
        {
            //加载产品类型
            List<DictionaryModel> dics = db.Dictionarys.GetList("Dic_Key like '105%'");
            List<SelectListItem> selectTypes = new List<SelectListItem>();

            selectTypes.Add(new SelectListItem() { Value = "000", Text = "请选择" });

            foreach (DictionaryModel item in dics)
            {
                if (item.Dic_Key.Length == 3) { continue; }
                if (item.Dic_Key == selectID)
                {
                    selectTypes.Add(new SelectListItem() { Value = item.Dic_Key.ToString(), Text = item.Dic_Value, Selected = true });
                }
                else
                {
                    selectTypes.Add(new SelectListItem() { Value = item.Dic_Key.ToString(), Text = item.Dic_Value });
                }
            }
            ViewData["selTypeCode"] = selectTypes;
        }

        /// <summary>
        /// 提交的表单name与model 对象属性名保持一致，可以直接赋值
        /// </summary>
        /// <param name="model"></param>
        /// <param name="action1"></param>
        /// <returns></returns>
        [ValidateInput(false)]
        public ActionResult Save(TemplateModel model)
        {
            string result = string.Empty;
            result = SaveStateEnum.OK.ToString();
            string filePath  = string.Empty;
            //上传文件
            if (Request.Files.Count>0)
            {
                string savePath = "/Template/";
                string fileTypes = "html,htm,txt";
                int maxSize = 1000000;
                HttpPostedFileBase file = Request.Files["fileField"];
                if (file == null)
                {
                    return Json(new { code = SaveStateEnum.NO.ToString(), msg = "请选择上传文件" });
                }

                string dirPath = Server.MapPath(savePath);
                if (!Directory.Exists(dirPath))
                {
                    Directory.CreateDirectory(dirPath);
                }

                string fileName = file.FileName;               
                string fileExt = Path.GetExtension(fileName).ToLower();
                //取消扩展名
               // fileName = fileName.Replace(fileExt, "");

                ArrayList fileTypeList = ArrayList.Adapter(fileTypes.Split(','));

                if (file.InputStream == null || file.InputStream.Length > maxSize)
                {
                    return Json(new { code = SaveStateEnum.NO.ToString(), msg = "文件大小超过上传限制" });
                }

                if (string.IsNullOrEmpty(fileExt) || Array.IndexOf(fileTypes.Split(','), fileExt.Substring(1).ToLower()) == -1)
                {
                    return Json(new { code = SaveStateEnum.NO.ToString(), msg = "上传文件扩展名非法" });
                }
                Random rd = new Random(DateTime.Now.GetHashCode());
                // string newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt;
               // string newFileName = string.Format("{0}_{1}_{2}{3}", fileName, DateTime.Now.ToString("yyyyMMdd"), rd.Next(1, 10000), fileExt);
                filePath = dirPath + fileName;
                file.SaveAs(filePath);

                //保存相对路径
                model.FilePath = savePath + fileName;

            }

           
            string message = "保存成功";
            try
            {
                if (model.action == ActionEnum.Create.ToString())
                {
                    if (db.Templates.Exists(model.Name))
                    {
                        return Json(new { code = SaveStateEnum.NO.ToString(), msg = "文件名:" + model.Name + "已存在!" });
                    }

                    db.Templates.Add(model);
                }
                else if (model.action == ActionEnum.Update.ToString())
                {
                    TemplateModel oldModel = db.Templates.GetModel(model.AID);
                    string oldTemplateFile = Server.MapPath(oldModel.FilePath);
                    if (System.IO.File.Exists(oldTemplateFile))
                    {
                        System.IO.File.Delete(oldTemplateFile);
                    }

                    db.Templates.Update(model);
                }
                else
                {
                    result = SaveStateEnum.NO.ToString();
                    message = "保存失败";
                    //删除对应文件
                    if (System.IO.File.Exists(filePath))
                    {
                        System.IO.File.Delete(filePath);
                    }
                }

            }
            catch (Exception ex)
            {
                LogHelper.Error(ex, "数据{0}失败", model.action);
                result = SaveStateEnum.NO.ToString();
                message = "保存失败";
                //删除对应文件
                if (System.IO.File.Exists(filePath))
                {
                    System.IO.File.Delete(filePath);
                }
            }

            return Json(new { code = result.ToString(), msg = message });
        }

        /// <summary>
        /// 上传模板文件
        /// </summary>
        /// <returns></returns>
       // [HttpPost]
       // [ValidateInput(false)]
        public ActionResult UploadFile(HttpPostedFileBase file)
        {
            string savePath = "/Template/";
           // string saveUrl = "/Content/UpImages/Products/";
            string fileTypes = "gif,jpg,jpeg,png,bmp,html,htm";
            int maxSize = 1000000;

            Hashtable hash = new Hashtable();

           // HttpPostedFileBase file = Request.Files["fileField"];
            if (file == null)
            {
                hash = new Hashtable();
                hash["error"] = 0;
                hash["msg"] = "请选择文件";
                return Json(hash);
            }

            string dirPath = Server.MapPath(savePath);
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }

            string fileName = file.FileName;
            string fileExt = Path.GetExtension(fileName).ToLower();

            ArrayList fileTypeList = ArrayList.Adapter(fileTypes.Split(','));

            if (file.InputStream == null || file.InputStream.Length > maxSize)
            {
                hash = new Hashtable();
                hash["error"] = 0;
                hash["msg"] = "上传文件大小超过限制";
                return Json(hash);
            }

            if (string.IsNullOrEmpty(fileExt) || Array.IndexOf(fileTypes.Split(','), fileExt.Substring(1).ToLower()) == -1)
            {
                hash = new Hashtable();
                hash["error"] = 0;
                hash["msg"] = "上传文件扩展名是不允许的扩展名";
                return Json(hash);
            }
            Random rd = new Random(DateTime.Now.GetHashCode());
            // string newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt;
            string newFileName = string.Format("{0}_{1}{2}{3}",fileName, DateTime.Now.ToString("yyyyMMdd"), rd.Next(1, 10000), fileExt);
            string filePath = dirPath + newFileName;
            file.SaveAs(filePath);
           // string fileUrl = saveUrl + newFileName;

            hash = new Hashtable();
            hash["error"] = 0;
            hash["msg"] = "文件上传成功!";

            return Json(hash, "text/html;charset=UTF-8");
        }

        public ActionResult Delete(string IDs)
        {
            string result = SaveStateEnum.NO.ToString();
            try
            {
                if (!string.IsNullOrEmpty(IDs))
                {
                    //删除模板文件
                    List<TemplateModel> list = db.Templates.GetList(string.Format("AID in ({0})", IDs));
                    foreach (TemplateModel item in list)
                    {
                        string filePath = Server.MapPath(item.FilePath);
                        if (System.IO.File.Exists(filePath))
                        {
                            System.IO.File.Delete(filePath);
                        }
                    }

                    IDs = IDs.TrimEnd(',');
                    db.Templates.DeleteList(IDs);
                    result = SaveStateEnum.OK.ToString();                    
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex, "删除数据失败!");
            }
            return Content(result);
        }

    }
}
